﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Common;
using Commons;
using Core;
using Core.Factory;
using Hangfire;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model;
using Newtonsoft.Json;
using NLog;
using WebApp.Models;
using WebApp.Serivces;
using WebApp.ViewModel;

namespace WebApp.ApiControllers
{
    /// <summary>
    /// 活动管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    public class ActivityController : Controller
    {
        private readonly IBaseService _baseService;
        private readonly IActivityService _activityService;
        private readonly IJoinService _joinService;
        private IHostingEnvironment hostingEnv;
        private readonly IFireServices _fireServices;
        private readonly Logger log = LogManager.GetCurrentClassLogger();
        private readonly string _appid = MyConfigurationSection.GetSite("AppID");
        private readonly string _secret = MyConfigurationSection.GetSite("Secret");
        private readonly string _template_id = MyConfigurationSection.GetSite("WeappTemplate");
        private readonly string _page = MyConfigurationSection.GetSite("ToPage");
        private readonly string _shareUrl = MyConfigurationSection.GetSite("ShareUrl");
        private readonly string _messageUrl= MyConfigurationSection.GetSite("MessageUrl");
        private readonly string _tokenUrl = MyConfigurationSection.GetSite("TokenUrl");
        private readonly string host = MyConfigurationSection.GetSite("Host");
        /// <summary>
        /// 活动
        /// </summary>
        /// <param name="baseService"></param>
        /// <param name="env"></param>
        /// <param name="activityService"></param>
        /// <param name="joinService"></param>
        /// <param name="fireServices"></param>
        public ActivityController(IBaseService baseService, IHostingEnvironment env, IActivityService activityService, IJoinService joinService, IFireServices fireServices)
        {
            _baseService = baseService;
            hostingEnv = env;
            _joinService = joinService;
            _activityService = activityService;
            _fireServices = fireServices;
        }
        /// <summary>
        /// 获取活动基本数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ResultModel GetBaseDate()
        {
            ResultModel result = new ResultModel();

            DataModel model = new DataModel();
            var ExchangeList = _baseService.GetList<T_ExchangeModel>(i => i.StateCode == StateCode.Enable.ToString(), o => o.Asc(i => i.Id));
            var PrizeList = _baseService.GetList<T_PrizeModel>(i => i.StateCode == StateCode.Enable.ToString(), o => o.Asc(i => i.Id));
            model.PrizeModel = PrizeList;
            model.ExchangeModel = ExchangeList;
            result.data = model;
            result.result = (int)MsgType.success;
            result.type = MsgType.success.ToString();
            result.code = "200";
            return result;

        }
        /// <summary>
        /// 获取活动列表
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="address"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultModel GetHome(int pageSize = 7, int pageIndex = 0, string address = "", int userId = 0)
        {
            ResultModel result = new ResultModel();
            try
            {
                List<T_Activity> data = new List<T_Activity>();
                int count = 0;
                Expression<Func<T_Activity, bool>> where = PredicateExtensionses.True<T_Activity>();

                where = where.And(i=>(i.ExpireDate!=null ? i.ExpireDate.Value > DateTime.Now : false) && i.IsOpen == 0
                && i.IsHome == 1);
                if (!string.IsNullOrWhiteSpace(address)) {
                    where = where.And(i=>(string.IsNullOrWhiteSpace(i.Location)?false:i.Location.Contains(address)));
                }
                //var users = _baseService.GetList<T_User>(i => i.ExpireDate.HasValue ? (i.ExpireDate.Value - DateTime.Now).Minutes > 0 : false);
                var list = _baseService.GetList(pageIndex, pageSize, ref count,
                    where, i => i.Desc(o => o.Points));

                data = list.ToList();
                bool isJoin = false;
                List<object> reList = new List<object>();
                foreach (var i in data)
                {
                    i.CoverPage = (host+i.CoverPage).Replace("\\", "/");
                    if (userId != 0)
                    {
                        isJoin = _baseService.GetCount<T_Join>(j => j.ActivityId == i.Id && j.UserId == userId) > 0;
                    }
                    reList.Add(new { isJoin, i.Address, i.CoverPage, i.CreateDate, i.DrawModelCode, i.ExchangeModelCode, i.ExpireDate, i.Id, i.IsHome, i.IsOpen, i.Location, i.OpenCount, i.OpenTime, i.Points, i.PrizeModelCode, i.Remark, i.Title, i.UserId });
                }
                result.data = reList;
                result.code = "200";
                result.result = (int)MsgType.success;
                result.type = MsgType.success.ToString();
                result.msg = "获取数据成功";
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;

                log.Error(ex, ex.Message);
            }
            return result;
        }
        /// <summary>
        /// 获取活动列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultModel GetActivityList(int pageIndex = 1, int pageSize = 20)
        {
            ResultModel result = new ResultModel();
            try
            {
                int count = 0;

                var list = _baseService.GetList<T_Activity>(pageIndex, pageSize, ref count, i => i.IsOpen == 0, i => i.Desc(o => o.CreateDate)).Take(6);
                foreach (var item in list)
                {
                    item.CoverPage = (host + item.CoverPage).Replace("\\", "/");
                }


                result.data = list;
                result.code = "200";
                result.result = (int)MsgType.success;
                result.type = MsgType.success.ToString();
                result.msg = "获取数据成功";
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;

                log.Error(ex, ex.Message);
            }
            return result;
        }
        /// <summary>
        /// 获取活动详情
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultModel GetActivity(int id, int userId = 0)
        {

            ResultModel result = new ResultModel();
            try
            {
                var model = _baseService.GetModel<T_Activity>(i => i.Id == id);
                model.CoverPage = (host + model.CoverPage).Replace("\\", "/");
                var details = _baseService.GetList<T_ActivityDetail>(i => i.ActivityId == model.Id);
                var graphics = _baseService.GetList<T_Graphic>(i => i.ActivityId == model.Id);
                foreach (var item in details)
                {
                    item.Url = (host + item.Url).Replace("\\", "/");
                }
                foreach (var item in graphics)
                {
                    if (!string.IsNullOrWhiteSpace(item.Img) && item.Index != -1)
                    {
                        item.Img = (host + item.Img).Replace("\\", "/");
                    }
                }
                var reModel = new
                {
                    activity = model,
                    details = details,
                    graphics = graphics,
                    isJoin = _baseService.GetCount<T_Join>(i => i.ActivityId == model.Id && i.UserId == userId) > 0
                };
                result.data = reModel;
                result.code = "200";
                result.result = (int)MsgType.success;
                result.type = MsgType.success.ToString();
                result.msg = "获取数据成功";
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;

                log.Error(ex, ex.Message);
            }
            return result;
        }
        /// <summary>
        /// 获取我发起列表
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultModel GetMyActivity(int userId, int pageIndex = 1, int pageSize = 20)
        {
            ResultModel result = new ResultModel();
            try
            {
                int count = 0;
                var list = _baseService.GetList<T_Activity>(pageIndex, pageSize, ref count, i => i.UserId == userId, i => i.Desc(o => o.CreateDate));
                foreach (var item in list)
                {
                    item.CoverPage = (host + item.CoverPage).Replace("\\", "/");
                }


                result.data = list;
                result.code = "200";
                result.result = (int)MsgType.success;
                result.type = MsgType.success.ToString();
                result.msg = "获取数据成功";
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;

                log.Error(ex, ex.Message);
            }
            return result;
        }
        /// <summary>
        /// 获取我参与
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultModel GetJoinActivity(int userId, int pageIndex = 1, int pageSize = 20)
        {
            ResultModel result = new ResultModel();
            try
            {
                int count = 0;
                var joins = _baseService.GetList<T_Join>(pageIndex, pageSize, ref count, i => i.UserId == userId, i => i.Desc(o => o.CreateDate)).Select(i => i.ActivityId);
                var list = _baseService.GetList<T_Activity>(i => joins.Contains(i.Id));
                foreach (var item in list)
                {
                    item.CoverPage = (host + item.CoverPage).Replace("\\", "/");
                }


                result.data = list;
                result.code = "200";
                result.result = (int)MsgType.success;
                result.type = MsgType.success.ToString();
                result.msg = "获取数据成功";
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;

                log.Error(ex, ex.Message);
            }
            return result;
        }
        /// <summary>
        /// 获取我中奖的
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultModel GetWinActivity(int userId, int pageIndex = 1, int pageSize = 20)
        {
            ResultModel result = new ResultModel();
            try
            {
                int count = 0;
                var joins = _baseService.GetList<T_Join>(pageIndex, pageSize, ref count, i => i.UserId == userId && i.IsLucky == 1, i => i.Desc(o => o.CreateDate)).Select(i => i.ActivityId);
                var list = _baseService.GetList<T_Activity>(i => joins.Contains(i.Id));
                foreach (var item in list)
                {
                    item.CoverPage = (host + item.CoverPage).Replace("\\", "/");
                }


                result.data = list;
                result.code = "200";
                result.result = (int)MsgType.success;
                result.type = MsgType.success.ToString();
                result.msg = "获取数据成功";
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;

                log.Error(ex, ex.Message);
            }
            return result;
        }
        /// <summary>
        /// 发起活动
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultModel InitActivity([FromBody]ActivityModel entity)
        {
            ResultModel result = new ResultModel();
            try
            {

                T_Activity re = _activityService.Add(entity.Activity, entity.Details, entity.Graphics, entity.FormId);
                var list = _baseService.GetList<T_ActivityDetail>(i => i.ActivityId == re.Id).Select(i => new { id = i.Id, index = i.Index });
                var graphics = _baseService.GetList<T_Graphic>(i => i.ActivityId == re.Id).Select(i => new { id = i.Id, index = i.Index });

                if (re.Id > 0)
                {
                    result.result = (int)MsgType.success;
                    result.type = MsgType.success.ToString();
                    result.code = "200";
                    result.msg = "参加成功";
                    result.data = new { id = re.Id, list = list.ToList(), graphics = graphics.ToList() };
                    if (entity.Activity.PrizeModelCode == Prize.ToTime.ToString())
                    {
                        BackgroundJob.Schedule(() => _fireServices.OpenActivity(entity.Activity.Id), entity.Activity.OpenTime.Value);
                    }
                    else
                    {
                        BackgroundJob.Schedule(() => _fireServices.OpenActivity(entity.Activity.Id), DateTime.Now.AddDays(7).AddMinutes(-10));
                    }
                }

            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                log.Error(ex, ex.Message);

            }
            return result;

        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="files"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultModel UploadFile(IList<IFormFile> files, int id)
        {
            log.Debug("files:" + files.Count);
            log.Debug("Request.Form.Files" + Request.Form.Files.Count);

            //必须加IList<IFormFile>否则files取值异常   不知道为啥
            ResultModel result = new ResultModel();
            try
            {
                var file = Request.Form.Files;
                string filePath = MyConfigurationSection.GetSite("ImgPath") + DateTime.Now.ToString("yyyy") + DateTime.Now.ToString("MM") + "\\";//hostingEnv.WebRootPath + $@"\Files\Files\";
                string path = hostingEnv.WebRootPath + filePath;
                string newPath = filePath + Request.Form.Files[0].FileName;
                var model = _activityService.Update(id, newPath);
                string rePath = "";
                rePath = FileHelper.UploadFile(Request.Form.Files[0], path);
                result.data = model.Url;
                result.result = (int)ResultType.success;
                result.code = "200";
                result.type = ResultType.success.ToString();
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                log.Error(ex, ex.Message);
            }
            return result;
        }
        /// <summary>
        /// 上传图文详情
        /// </summary>
        /// <param name="files"></param>
        /// <param name="id">图文 id</param>
        /// <returns></returns>
        [HttpPost]
        public ResultModel UploadGraphic(IList<IFormFile> files, int id)
        {


            //必须加IList<IFormFile>否则files取值异常   不知道为啥
            ResultModel result = new ResultModel();
            try
            {
                log.Debug("files:" + files.Count);
                log.Debug("Request.Form.Files" + Request.Form.Files.Count);
                var file = Request.Form.Files;
                string filePath = MyConfigurationSection.GetSite("ImgPath") + DateTime.Now.ToString("yyyy") + DateTime.Now.ToString("MM") + "\\";//hostingEnv.WebRootPath + $@"\Files\Files\";
                string path = hostingEnv.WebRootPath + filePath;
                string newPath = filePath + Request.Form.Files[0].FileName;

                var model = _activityService.UpdateGraphic(id, newPath);
                if (model != null)
                {
                    string rePath = "";
                    rePath = FileHelper.UploadFile(Request.Form.Files[0], path);
                    result.result = (int)ResultType.success;
                    result.code = "200";
                    result.type = ResultType.success.ToString();
                    result.msg = "上传成功";
                }
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                log.Error(ex, ex.Message);
            }
            return result;
        }
        /// <summary>
        /// 判断是否能发布和购买
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ResultModel GetRemaining(int userId)
        {
            ResultModel result = new ResultModel();
            var list = _baseService.GetList<T_User>(i => (i.ExpireDate.HasValue ? (i.ExpireDate.Value - DateTime.Now).Minutes > 0 : false));

            var activitys = _baseService.GetList<T_Activity>(i => (i.ExpireDate.HasValue ? i.ExpireDate.Value > DateTime.Now : false) && i.IsHome == 1 && i.IsOpen == 0 && list.FirstOrDefault(u => u.Id == i.UserId) != null);
            //判断是否是vip用户
            if (list.Where(i => i.Id == userId).Count() > 0)
            {
                //判断已发起的活动个数
                if (activitys.Count >= 21)
                {
                    //不能发
                    result.data = 0;
                }
                //当前用户是否发起活动
                else if (activitys.Where(i => i.UserId == userId).Count() > 0)
                {
                    result.data = 0;
                }
                //则可以发送
                else
                {
                    //可以发
                    result.data = 1;
                }
            }
            //判断vip个数 
            else if (list.Count >= 21)
            {
                result.data = 0;
            }
            //则调转购买
            else
            {
                //需购买
                result.data = 2;
            }

            result.result = (int)ResultType.success;
            result.code = "200";
            result.type = ResultType.success.ToString();
            result.msg = "获取成功";
            return result;
        }
        /// <summary>
        /// 参加活动
        /// </summary>
        /// <param name="entity"></param>
        [HttpPost]
        public ResultModel JoinActivity(JoinModel entity)
        {
            ResultModel result = new ResultModel();
            try
            {
                T_Join t_Join = new T_Join();
                t_Join.ActivityDetailId = entity.ActivityDetailId;
                t_Join.ActivityId = entity.ActivityId;
                t_Join.ExchangeCode = entity.ExchangeCode;
                t_Join.IsLucky = entity.IsLucky;
                t_Join.UserId = entity.UserId;
                var model = _activityService.JoinActivity(t_Join, entity.FormId);

                if (model.PrizeModelCode == Prize.ToNum.ToString())
                {
                    int num = _baseService.GetCount<T_Join>(i => i.ActivityId == t_Join.ActivityId);
                    if (num == model.OpenCount)
                    {
                        _fireServices.OpenActivity(model.Id);
                    }
                    else if(num>model.OpenCount){
                        result.result = (int)MsgType.error;
                        result.type = MsgType.error.ToString();
                        result.code = "500";
                        result.msg = "活动已截止！";
                        return result;
                    }
                }
                else
                {
                    if (model.OpenTime<DateTime.Now) {
                        result.result = (int)MsgType.error;
                        result.type = MsgType.error.ToString();
                        result.code = "500";
                        result.msg = "活动已截止！";
                        return result;
                    }
                }
                result.result = (int)MsgType.success;
                result.type = MsgType.success.ToString();
                result.code = "200";
                result.msg = "参加活动成功";
            }
            catch (Exception ex)
            {
                log.Error(ex, ex.Message);
                result.msg = "参与失败！请联系客服！";
            }
            return result;
        }
        /// <summary>
        /// 手动开奖
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="activityId"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultModel ManualActivity(int userId, int activityId)
        {
            ResultModel result = new ResultModel();
            try
            {
                var model = _baseService.GetModel<T_Activity>(i => i.Id == activityId && i.UserId == userId);
                if (model.PrizeModelCode == Prize.ToManual.ToString())
                {
                    //_fireServices.SendTempMsg(model.Id);
                    result.result = (int)MsgType.success;
                    result.type = MsgType.success.ToString();
                    result.code = "200";
                }

            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                log.Error(ex, ex.Message);

            }
            return result;
        }
        #region old open
        ///// <summary>
        ///// 定时开机
        ///// </summary>
        ///// <param name="activityId"></param>
        //private void OpenActivity(int activityId)
        //{
        //    DateTime time = DateTime.Now;
        //    var joins = _baseService.GetList<T_Join>(i => i.ActivityId == activityId);
        //    var activity = _baseService.GetModel<T_Activity>(i => i.Id == activityId);
        //    var details = _baseService.GetList<T_ActivityDetail>(i => i.ActivityId == activityId);
        //    Random random = new Random();
        //    if (activity != null && activity.IsOpen != 0)
        //    {
        //        return;
        //    }
        //    if (activity.OpenCount != null)
        //    {
        //        if (activity.OpenCount.Value > 0 && activity.OpenCount > joins.Count)
        //        {
        //            //人数不够，未开奖
        //            var dataA = new { keyword1 = new { value = "活动指南" }, keyword2 = new { value = activity.Title }, keyword3 = new { value = time }, keyword4 = new { value = "您发起的活动未开奖，因参与人数不够，点击查看详情" } };
        //            SendMsg(_baseService.GetModel<T_User>(u => u.Id == activity.UserId).WxOpenId, dataA);
        //            _activityService.UpdateOpen(activity.Id, 2);
        //            return;
        //        }
        //    }
        //    if (details == null || details.Count > 0)
        //    {
        //        //未找到活动信息
        //        var dataA = new { keyword1 = new { value = "活动指南" }, keyword2 = new { value = activity.Title }, keyword3 = new { value = time }, keyword4 = new { value = "点击查看详情" } };
        //        SendMsg(_baseService.GetModel<T_User>(u => u.Id == activity.UserId).WxOpenId, dataA);
        //        _activityService.UpdateOpen(activity.Id, 2);
        //        return;
        //    }
        //    if (joins == null || joins.Count > 0)
        //    {
        //        //无人参加活动
        //        //为发起者发送开奖通知
        //        var dataB = new { keyword1 = new { value = "活动指南" }, keyword2 = new { value = activity.Title }, keyword3 = new { value = time }, keyword4 = new { value = "您发起的活动未开奖，因参与人数为0，点击查看详情" } };
        //        SendMsg(_baseService.GetModel<T_User>(u => u.Id == activity.UserId).WxOpenId, dataB);
        //        _activityService.UpdateOpen(activity.Id, 2);
        //        return;
        //    }
        //    List<int> lucks = new List<int>();
        //    List<T_Join> joinLucks = new List<T_Join>();
        //    foreach (var item in details)
        //    {
        //        var number = item.Number;
        //        for (int i = 0; i < Convert.ToInt32(number); i++)
        //        {
        //            int index = GetRandom(lucks, joins.Count);
        //            lucks.Add(index);
        //            T_Join join = joins[index];
        //            join.IsLucky = 1;
        //            join.ActivityDetailId = item.Id;
        //            joinLucks.Add(join);
        //        }
        //    }
        //    foreach (var item in joins)
        //    {
        //        string openid = _baseService.GetModel<T_User>(u => u.Id == item.UserId).WxOpenId;
        //        var data = new { keyword1 = new { value = "活动指南" }, keyword2 = new { value = activity.Title }, keyword3 = new { value = time }, keyword4 = new { value = "点击查看中奖名单" } };
        //        SendMsg(openid, data);
        //    }
        //    //为发起者发送开奖通知
        //    var data2 = new { keyword1 = new { value = "活动指南" }, keyword2 = new { value = activity.Title }, keyword3 = new { value = time }, keyword4 = new { value = "点击查看中奖名单" } };
        //    SendMsg(_baseService.GetModel<T_User>(u => u.Id == activity.UserId).WxOpenId, data2);
        //    _activityService.UpdateOpen(activity.Id, 1);
        //    _joinService.UpdateJoins(joinLucks);
        //}
        ///// <summary>
        ///// GetRandom
        ///// </summary>
        ///// <param name="indexs"></param>
        ///// <param name="end"></param>
        ///// <returns></returns>
        //private int GetRandom(List<int> indexs, int end)
        //{
        //    Random random = new Random();

        //    int index = random.Next(1, end + 1);
        //    if (indexs.Contains(index))
        //    {
        //        index = GetRandom(indexs, end);
        //    }
        //    return index;
        //}
        ///// <summary>
        ///// 为小程序推送消息
        ///// </summary>
        //private void SendMsg(string touser, object data)
        //{
        //    string accessToken = GetAccessToken();
        //    HttpClient client = new HttpClient();
        //    var formid = _activityService.GetFormId();
        //    TemplateMessage templateMessage = new TemplateMessage();
        //    templateMessage.touser = touser;
        //    templateMessage.access_token = accessToken;
        //    templateMessage.form_id = formid;
        //    templateMessage.page = _page;
        //    templateMessage.template_id = _template_id;
        //    templateMessage.emphasis_keyword = "";
        //    templateMessage.data = data;
        //    HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(templateMessage));
        //    httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        //    HttpResponseMessage response = client.PostAsync(_messageUrl + accessToken, httpContent).Result;
        //    string result = response.Content.ReadAsStringAsync().Result;
        //    client.Dispose();
        //    TemplateResult access = Newtonsoft.Json.JsonConvert.DeserializeObject<TemplateResult>(result);
        //    if (access.errcode == 0)
        //    {
        //        _activityService.UpdateForm(formid);
        //    }
        //}
        #endregion
        /// <summary>
        /// 微信接口凭证
        /// </summary>
        /// <returns></returns>
        private string GetAccessToken()
        {
            HttpClient client = new HttpClient();
            HttpResponseMessage response = client.GetAsync(_tokenUrl + _appid + "&secret=" + _secret).Result;
            string result = response.Content.ReadAsStringAsync().Result;
            client.Dispose();
            AccessModel access = Newtonsoft.Json.JsonConvert.DeserializeObject<AccessModel>(result);
            if (access != null && access.errcode == 0)
            {
                return access.access_token;
            }
            return "";
        }
        /// <summary>
        /// 获取参加活动的用户
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultModel GetJoinActivityUser(int id, int pageIndex = 1, int pageSize = 20)
        {
            ResultModel result = new ResultModel();
            try
            {
                int count = 0;
                var join = _baseService.GetList<T_Join>(pageIndex, pageSize, ref count, i => i.ActivityId == id);
                var users = _baseService.GetList<T_User>(i => join.Select(j => j.UserId).Contains(i.Id));

                result.data = new { users = users.Select(i => new { id = i.Id, photo = i.WxPhoto }), count };
                result.code = "200";
                result.result = (int)MsgType.success;
                result.type = MsgType.success.ToString();
                result.msg = "获取数据成功";
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;

                log.Error(ex, ex.Message);
            }
            return result;
        }
        /// <summary>
        /// 中奖后设置收货地址
        /// </summary>
        /// <param name="addressModel"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultModel SetAddress(AddressModel addressModel)
        {
            ResultModel result = new ResultModel();
            try
            {
                _joinService.SetAddress(addressModel.UserId, addressModel.ActivityId, addressModel.Address);
                result.code = "200";
                result.result = (int)MsgType.success;
                result.type = MsgType.success.ToString();
                result.msg = "地址更新成功";
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;

                log.Error(ex, ex.Message);
            }
            return result;
        }
        /// <summary>
        /// 获取中奖名单
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultModel GetLuckUser(int id, int pageIndex = 1, int pageSize = 20)
        {
            ResultModel result = new ResultModel();
            try
            {
                int count = 0;
                var join = _baseService.GetList<T_Join>(pageIndex, pageSize, ref count, i => i.ActivityId == id && i.IsLucky != 0, o => o.Asc(i => i.ActivityDetailId));

                List<LuckModel> reList = new List<LuckModel>();
                foreach (var item in join.GroupBy(i => i.ActivityDetailId))
                {
                    var activity = _baseService.GetModel<T_ActivityDetail>(a => a.Id == item.Key);
                    LuckModel luck = new LuckModel();
                    luck.detail = new { id = activity.Id, title = activity.Title, number = activity.Number };
                    luck.users = join.Where(i => i.ActivityDetailId == item.Key).Select(i => new
                    {
                        i.ActivityDetailId,
                        i.ActivityId,
                        i.Address,
                        i.ExchangeCode,
                        i.Id,
                        i.UserId,
                        UserName = _baseService.GetModel<T_User>(u => u.Id == i.UserId).WxName,
                        WxPhoto = _baseService.GetModel<T_User>(u => u.Id == i.UserId).WxPhoto

                    }).ToList();
                    luck.count = join.Where(i => i.ActivityDetailId == item.Key).Count();
                    reList.Add(luck);
                }


                result.data = new { reList, count = count };
                result.code = "200";
                result.result = (int)MsgType.success;
                result.type = MsgType.success.ToString();
                result.msg = "获取数据成功";
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;

                log.Error(ex, ex.Message);
            }
            return result;
        }
        /// <summary>
        /// 判断是否中奖
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="activityId"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultModel IsLucky(int userId, int activityId)
        {
            ResultModel result = new ResultModel();
            try
            {
                var join = _baseService.GetModel<T_Join>(i => i.ActivityId == activityId && i.IsLucky != 0 && i.UserId == userId);

                result.data = join;
                result.code = "200";
                result.result = (int)MsgType.success;
                result.type = MsgType.success.ToString();
                result.msg = "获取数据成功";
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;

                log.Error(ex, ex.Message);
            }
            return result;
        }
        /// <summary>
        /// 验证兑奖码
        /// </summary>
        /// <param name="code"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultModel ValiDateyCode(string code, int userId)
        {
            ResultModel result = new ResultModel();
            try
            {
                var join = _baseService.GetModel<T_Join>(i => i.ExchangeCode == code);
                var activity = _baseService.GetModel<T_Activity>(i => i.UserId == userId && join.ActivityId == i.Id);
                var detail = _baseService.GetModel<T_ActivityDetail>(i => i.Id == join.ActivityDetailId);
                if (join == null)
                {
                    result.data = null;
                    result.code = "500";
                    result.result = (int)MsgType.error;
                    result.type = MsgType.error.ToString();
                    result.msg = "未找到兑奖码：" + code;
                }
                else if (activity == null)
                {
                    result.data = null;
                    result.code = "500";
                    result.result = (int)MsgType.error;
                    result.type = MsgType.error.ToString();
                    result.msg = "当前商户发起的活动中，未找到该兑换码：" + code;
                }
                else
                {
                    if (join.IsExchange != 0)
                    {
                        result.data = null;
                        result.code = "500";
                        result.result = (int)MsgType.error;
                        result.type = MsgType.error.ToString();
                        result.msg = "兑奖码：" + code + "已经兑换！";
                    }
                    else
                    {

                        result.data = new { Url=(host + detail.Url).Replace("\\", "/"), detail.Title };
                        result.code = "200";
                        result.result = (int)MsgType.success;
                        result.type = MsgType.success.ToString();

                    }
                }

            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.code = "500";
                result.result = (int)MsgType.error;
                result.type = MsgType.error.ToString();
                log.Error(ex, ex.Message);
            }
            return result;
        }
        /// <summary>
        /// 核销兑奖码
        /// </summary>
        /// <param name="code"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultModel UseExchangeCode(string code, int userId)
        {
            ResultModel result = new ResultModel();
            try
            {
                var joins = _baseService.GetModel<T_Join>(i => i.ExchangeCode == code);

                var activity = _baseService.GetModel<T_Activity>(i => i.UserId == userId && joins.ActivityId == i.Id);

                var join = _joinService.UseExchangeCode(code);
                if (activity == null)
                {
                    result.data = false;
                    result.code = "200";
                    result.result = (int)MsgType.success;
                    result.type = MsgType.success.ToString();
                    result.msg = "当前商户发起的活动中，未找到该兑换码：" + code;
                }
                else if (join == null)
                {
                    result.data = false;

                    result.code = "500";
                    result.result = (int)MsgType.error;
                    result.type = MsgType.error.ToString();
                    result.msg = "兑奖码不存在,请验证：" + code;
                }
                else
                {
                    result.data = true;
                    result.code = "200";
                    result.result = (int)MsgType.success;
                    result.type = MsgType.success.ToString();
                    result.msg = "兑奖码核销成功：" + code;
                }
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;

                log.Error(ex, ex.Message);
            }
            return result;
        }
        /// <summary>
        /// 重新上首页
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="activityId"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultModel SetHome(int userId, int activityId)
        {
            ResultModel result = new ResultModel();
            try
            {
                _activityService.SetHome(userId, activityId);

                result.code = "200";
                result.result = (int)MsgType.success;
                result.type = MsgType.success.ToString();
                result.msg = "置顶首页成功";
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;

                log.Error(ex, ex.Message);
            }
            return result;
        }
        /// <summary>
        /// 生产分享图
        /// </summary>
        /// <param name="share"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultModel BuildShare(ShareModel share)
        {
            ResultModel result = new ResultModel();
            try
            {
                HttpClient client = new HttpClient();

                string accessToken = GetAccessToken();
                HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(share));
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                HttpResponseMessage response = client.PostAsync(_shareUrl + accessToken, httpContent).Result;


                try
                {
                    var re = response.Content.ReadAsByteArrayAsync().Result;
                    client.Dispose();

                    result.data = re;
                    result.code = "200";
                    result.result = (int)MsgType.success;
                    result.type = MsgType.success.ToString();
                    result.msg = "生成成功";

                }
                catch (Exception)
                {
                    ReShareModel reShare = JsonConvert.DeserializeObject<ReShareModel>(response.Content.ReadAsStringAsync().Result);
                    if (reShare != null)
                    {
                        result.code = reShare.errcode;
                        result.result = (int)MsgType.error;
                        result.type = MsgType.error.ToString();
                        result.msg = reShare.errmsg;
                    }
                }
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;

                log.Error(ex, ex.Message);
            }
            return result;
        }

    }
}
